﻿using Clipper2Lib;
using PointAsLine;
using System;
using System.Collections.Generic;

public class SelfIntersectingPolygonMerge
{
    internal static List<Polyline> MergeSelfIntersectingPolygon(List<Polyline> simplifiedSegments)
    {
        for (var i = simplifiedSegments.Count - 1; i >= 0; i--)
        {
            simplifiedSegments[i] = MergeSelfIntersectingPolygon(simplifiedSegments[i]);
        }
        return simplifiedSegments;
    }

    public static Polyline MergeSelfIntersectingPolygon(Polyline polygon)
    {
        // 1. 将 PointF 转换为 Clipper2 的 PathD 结构
        PathD path = new PathD(polygon.Count);
        foreach (var pt in polygon.Points)
        {
            path.Add(new PointD(pt.X, pt.Y));
        }

        // 2. 使用 Clipper 的 Union 操作（即使只有一个多边形）
        PathsD solution = Clipper.Union(new PathsD { path }, FillRule.EvenOdd);

        // 3. 返回面积最大的多边形（即外边界）
        PathD largestPolygon = GetLargestPolygon(solution);

        // 4. 转换回 PointF 列表
        List<PointF2G> result = new List<PointF2G>();
        foreach (var pt in largestPolygon)
        {
            result.Add(new PointF2G((float)pt.x, (float)pt.y));
        }
        if (result.Count > 0)
            result.Add(result[0]);

        return new Polyline() { Points = result, GroupIndex = polygon.GroupIndex };
    }

    // 从多个多边形中提取面积最大的一个
    private static PathD GetLargestPolygon(PathsD polygons)
    {
        if (polygons.Count == 0)
            return new PathD();

        PathD largest = polygons[0];
        double maxArea = Math.Abs(Clipper.Area(largest));

        for (int i = 1; i < polygons.Count; i++)
        {
            double area = Math.Abs(Clipper.Area(polygons[i]));
            if (area > maxArea)
            {
                maxArea = area;
                largest = polygons[i];
            }
        }

        return largest;
    }
}